package com.pri.chat.fragment.daohang;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.entity.WishListBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.pri.chat.R;
import com.pri.chat.activity.OtherPeopleMsgActivity;
import com.pri.chat.activity.PeopleMsgActivity;
import com.pri.chat.activity.ReleaseJuBaoAcctivity;
import com.pri.chat.activity.ShareMemberActivity;
import com.pri.chat.activity.WishMsgActivity;
import com.pri.chat.adapter.WishAllAdapter;
import com.pri.chat.dialog.DialogUtil;
import com.pri.chat.event.EventTag;
import com.pri.chat.event.MessageEvent;
import com.pri.chat.model.WishModel;
import com.pri.chat.utils.Des3Util;
import com.pri.chat.utils.GlideEngine;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.fragment.FragmentLazy;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：添加类的描述
 *
 * @author
 * @time 2020/4/28
 */
public class WishAllFragment extends FragmentLazy implements BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.OnItemClickListener {
    @BindView(R.id.rec_main)
    RecyclerView recMain;
    @BindView(R.id.none)
    ImageView none;
    @BindView(R.id.srl_all)
    SmartRefreshLayout srlAll;
    Unbinder unbinder;
    private List<WishListBean> mList;
    private WishAllAdapter mAdapter;
    private int type;
    private int page = 1;
    private boolean isShowDialog = false;

    public static WishAllFragment getInstance(int type) {
        WishAllFragment fragment = new WishAllFragment();
        fragment.type = type;
        return fragment;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        unbinder.unbind();
    }

    @Override
    protected View initViews(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle savedInstanceState) {
        View view = layoutInflater.inflate(R.layout.fragment_wish_list_layout, viewGroup, false);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        srlAll.setEnableLoadmore(true);
        initLayout();
        initSrl();
        return view;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshData(MessageEvent messageEvent) {
        if (messageEvent.getTag().equals(EventTag.WISH)) {
            refresh();
        }
    }

    public void updateWish(WishListBean wish) {
        if (mList != null) {
            for (int i = 0; i < mList.size(); i++) {
                if (wish.getId().equals(mList.get(i).getId())) {
                    mAdapter.setData(i, wish);
                    break;
                }
            }
        }
    }

    public void deteleWish(WishListBean wish) {
        if (mList != null) {
            for (int i = 0; i < mList.size(); i++) {
                if (wish.getId().equals(mList.get(i).getId())) {
                    mList.remove(i);
                    mAdapter.notifyDataSetChanged();
                    break;
                }
            }
        }
    }

    private void initLayout() {
        mList = new ArrayList<>();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        recMain.setLayoutManager(linearLayoutManager);
        mAdapter = new WishAllAdapter(R.layout.item_wish, mList);
        recMain.setAdapter(mAdapter);
        mAdapter.setOnItemChildClickListener(this);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnImageClickListener(new WishAllAdapter.OnImageClickListener() {
            @Override
            public void onItemClick(View view, int c_pos, int f_pos) {
                PictureSelector.create(mContext)
                        .themeStyle(R.style.picture_default_style)
                        .isNotPreviewDownload(true)
                        .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                        .openExternalPreview(c_pos, mList.get(f_pos).getMediaList());
            }
        });

    }

    @Override
    protected void initData() {
        SubscriberOnNextListener<BaseBean<List<WishListBean>>> onNextListener = baseBean -> {
            if (baseBean.getData().isEmpty() && page == 1) {
                none.setVisibility(View.VISIBLE);
                mAdapter.notifyDataSetChanged();
                srlAll.setEnableLoadmore(false);
            } else {
                none.setVisibility(View.INVISIBLE);
                mList.addAll(baseBean.getData());
                for (int i = 0; i < mList.size(); i++) {
                    String[] imgs = mList.get(i).getPicList().split(",");
                    List<String> list = new ArrayList<>();
                    List<LocalMedia> mediaList = new ArrayList<>();
                    for (int j = 0; j < imgs.length; j++) {
                        LocalMedia localMedia = new LocalMedia();
                        list.add(imgs[j]);
                        localMedia.setPath(imgs[j]);
                        mediaList.add(localMedia);

                    }
                    mList.get(i).setImgs(list);
                    mList.get(i).setMediaList(mediaList);
                }
                mAdapter.notifyDataSetChanged();
                if (baseBean.getData().size() < 10) {
                    srlAll.setEnableLoadmore(false);
                }
            }
        };
        Map<String, Object> params = new HashMap<>();
        params.put("otherMemberId", SharedHelper.readId(mContext));
        params.put("pageIndex", page);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().listWish(new ProgressSubscriber<>(onNextListener, mContext, isShowDialog), requestBody);
    }

    private void initSrl() {
        srlAll.setOnRefreshListener(refresh_layout -> {
            refresh_layout.finishRefresh(1000);
            refresh();
        });
        srlAll.setOnLoadmoreListener(refresh_layout -> {
            refresh_layout.finishLoadmore(1000);
            isShowDialog = false;
            page++;
//            initData();
        });
    }

    private void refresh() {
        page = 1;
        isShowDialog = false;
        mList.clear();
        mAdapter.notifyDataSetChanged();
//        initData();
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.tv_wish_go:
                TextView tv = (TextView) view;
                if (tv.getText().toString().equals(" 完成愿望 ")) {
                    finishWish(position);
                } else {
                    if (mList.get(position).getCanHelp() == 0) {
                        httpGoWish(position);
                    }
                }
                break;
            case R.id.iv_logo:
                if (mList.get(position).getMemberId().equals(SharedHelper.readId(mContext))) {
                    RxActivityTool.skipActivity(mContext, PeopleMsgActivity.class);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", mList.get(position).getMemberId());
                    RxActivityTool.skipActivity(mContext, OtherPeopleMsgActivity.class, bundle);
                }
                break;
            case R.id.iv_share:
                initShareDialog(mList.get(position).getPicList(), position);
                break;
        }
    }

    private void httpGoWish(int pos) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal("已通知对方");
            mList.get(pos).setCanHelp(1);
            mAdapter.notifyDataSetChanged();
        };
        WishModel dtModel = new WishModel(type);
        dtModel.setMemberId(SharedHelper.readId(mContext));
        dtModel.setWishId(mList.get(pos).getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(dtModel));
        HttpMethods.getInstance().saveWishHelp(new ProgressSubscriber<>(onNextListener, mContext, isShowDialog), requestBody);
    }

    private void deleteWish(int pos) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal("删除成功！");
            mAdapter.remove(pos);
        };
        Map<String, Object> params = new HashMap<>();
        params.put("id", mList.get(pos).getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().deleteWish(new ProgressSubscriber<>(onNextListener, mContext, isShowDialog), requestBody);
    }

    private void finishWish(int pos) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal("操作成功");
            mList.get(pos).setStatus(1);
            mAdapter.notifyDataSetChanged();
        };
        Map<String, Object> params = new HashMap<>();
        params.put("id", mList.get(pos).getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().finishWish(new ProgressSubscriber<>(onNextListener, mContext, isShowDialog), requestBody);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        Intent intent = new Intent(mContext, WishMsgActivity.class);
        Bundle bundle_2 = new Bundle();
        bundle_2.putParcelable("wish", mList.get(position));
        bundle_2.putInt("position", position);
        intent.putExtras(bundle_2);
        startActivityForResult(intent, 1);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 10) {
                int postion = data.getIntExtra("position", -1);
                WishListBean bean = data.getParcelableExtra("bean");
                mAdapter.setData(postion, bean);
            }
        }
    }

    private Dialog mShareDialog;

    private void initShareDialog(String path, int pos) {
        String memberId = SharedHelper.readId(mContext);
        String listMemberId = mList.get(pos).getMemberId();
        int type = 1;
        if (listMemberId.equals(memberId)) {
            type = 2;
        }
        mShareDialog = DialogUtil.getInstance().showShareDialog(mContext, type);
        TextView title = mShareDialog.findViewById(R.id.title);
        title.setText("让好友帮忙实现");
        DialogUtil.getInstance().setOnShareClickListener(new DialogUtil.OnShareClickListener() {
            @Override
            public void qqOnClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("id", mList.get(pos).getId());
                bundle.putString("image", path);
                bundle.putString("title", mList.get(pos).getMemberName());
                bundle.putString("content", mList.get(pos).getContent());
                RxActivityTool.skipActivity(mContext, ShareMemberActivity.class, bundle);
                mShareDialog.dismiss();
                mShareDialog.dismiss();
            }

            @Override
            public void circleOnClick(View v) {
                mShareDialog.dismiss();
                DialogUtil.getInstance().shareWechatMoments(path, HttpMethods.SHARE_TITLE, mList.get(pos).getContent(), HttpMethods.SHARE_URL);
            }

            @Override
            public void qZoneOnClick(View v) {
                mShareDialog.dismiss();
                //删除操作
                deleteWish(pos);
            }

            @Override
            public void weixinOnClick(View v) {
                mShareDialog.dismiss();
                DialogUtil.getInstance().shareWeChat(path, HttpMethods.SHARE_TITLE, mList.get(pos).getContent(), HttpMethods.SHARE_URL);
            }

            @Override
            public void jubaoOnClick(View v) {
                mShareDialog.dismiss();

                Bundle bundle = new Bundle();
                bundle.putString("id",mList.get(pos).getId());
                bundle.putString("type","2");
                RxActivityTool.skipActivity(mContext, ReleaseJuBaoAcctivity.class,bundle);

            }
        });
        mShareDialog.show();
    }
}

